package com.itheima.dao;

import com.itheima.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class UserDao {

    /**
     * 添加
     * @param user
     */
    public   void  addUser(User user){
        /*try {
            Class.forName("com.mysql.jdbc.Driver");

           Connection conn =  DriverManager.getConnection("jdbc:mysql://39.106.185.194:3306/heima","root","WXY201130@outlook.com");

            PreparedStatement preparedStatement = conn.prepareStatement("insert  into  t_user  values(null,?,?)");

            preparedStatement.setString(1,user.getName());
            preparedStatement.setInt(2,user.getAge());
            preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("mybatisConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //sqlsession开启事务
            SqlSession sqlSession = sqlSessionFactory.openSession(true);

            sqlSession.insert("xxxx.insert",user);

            sqlSession.close();
            resourceAsStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public List<User> findAll() {
        List<User> users = null;
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("mybatisConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //sqlsession开启事务
            SqlSession sqlSession = sqlSessionFactory.openSession(true);

            users = sqlSession.selectList("xxxx.findAll");
            sqlSession.close();
            resourceAsStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  users;
    }
}
